<template>
  <div class="zy-content">
      <div class="detailInfo">
        <span class="title">{{$route.query.itemProject}}</span>
        <template v-if="!beconfirmed">
          <div class="result resultSpan">
            <span class="text">{{$t('maintenance.Result')}}</span>
            <div class="resultBtn">
              <template v-for="item in resultBtn">
          <span :class="[{'btn_item_avtive': item.active},'btn_item']"
                @click="btnCick(item)">
            {{item.title}}
            <template v-if="item.active">
              <span class="imgBox">
                 <img src="@/assets/imgs/maintenance/resultbtn.png" alt=""/>
              </span>
            </template>
          </span>
              </template>
            </div>
          </div>
          <div class="recordText">
            <span class="text">{{$t('maintenance.Record')}}</span>
            <div class="textInfo">
              <van-field
                  v-model="resultValue"
                  rows="2"
                  :type="numberStatus"
                  @input="assetsChange"
                  placeholder="请进行描述"
              />
              <span class="imgBox">
        <img src="@/assets/imgs/maintenance/description.png" alt=""/>
      </span>
            </div>
          </div>
          <div class="videoBox">
            <span class="text">{{$t('maintenance.Upload')}}</span>
            <Row class="videoList">
              <template v-for="(item,index) in fileList">
                <Col span="2" class="itemCol">
                  <van-badge>
                    <template>
            <span class="item" @click="previewClicjk(item,index)">
             <template v-if="!item.filePath.includes('video')">
                <img :src="util.filePathToUrl(item.filePath)" alt=""/>
             </template>
              <template>
                 <video preload="auto" loop autoplay muted>
                 <source :src="util.filePathToUrl(item.filePath)" type="video/mp4">
             </video>
              </template>
            </span>
                    </template>
                    <template #content>
                      <van-icon @click="delFujian(item)" name="cross" class="badge-icon" />
                    </template>
                  </van-badge>
                </Col>
              </template>
              <Col span="2" class="itemCol videoCol">
                <van-uploader
                    v-model="fileListArr"
                    accept="*"
                    :after-read="afterRead"
                    @oversize="oversize"
                >
                  <template #preview-cover="{ file }">
                    <span class="text">{{$t('maintenance.New')}}</span>
                  </template>
                </van-uploader>
              </Col>
            </Row>
          </div>
        </template>
        <template v-else>
         <Row>
           <div style="display: flex;justify-content: center;align-items: center;">
             <Col span="6">
               <div class="result">
                 <span class="text">{{$t('maintenance.Bythetime')}}</span>
                 <span class="textInfo">{{tarGetObj.taskEndTime}}</span>
               </div>
             </Col>
             <Col span="6">
               <div class="result">
                 <span class="text">{{$t('maintenance.MaintenanceItem')}}</span>
                 <span class="textInfo">{{tarGetObj.itemProject}}</span>
               </div>
             </Col>
             <Col span="6">
               <div class="result">
                 <span class="text">{{$t('maintenance.MaintenanceMethod')}}</span>
                 <span class="textInfo">{{tarGetObj.itemMethod}}</span>
               </div>
             </Col>
             <Col span="6">
               <div class="result">
                 <span class="text">{{$t('maintenance.usetools')}}</span>
                 <span class="textInfo" @click="checkusetool">
             <span>{{$t('maintenance.Query')}} <van-badge color="#1989fa"
                                                          :content="tarGetObj.toolNum" max="99" /></span>
              <van-icon name="arrow" />
        </span>
               </div>
             </Col>
           </div>
           <div style="display: flex;justify-content: center;align-items: center;">
             <Col span="6">
               <div class="result">
                 <span class="text">{{$t('maintenance.threshold')}}</span>
                 <span class="textInfo">
          <template v-if="tarGetObj.minValue && tarGetObj.maxValue">{{`${tarGetObj.minValue} - ${tarGetObj.maxValue} 个` }}</template>
          <template v-else>{{$t('maintenance.none')}}</template>
        </span>
               </div>
             </Col>
             <Col span="6">
               <div class="result">
                 <span class="text">{{$t('maintenance.Result')}}</span>
                 <span class="textInfo">
         <template v-if="tarGetObj.resultStatus">{{tarGetObj.resultStatus}}</template>
          <template v-else>{{$t('maintenance.none')}}</template>
        </span>
               </div>
             </Col>
             <Col span="6">
               <div class="result">
                 <span class="text">{{$t('maintenance.Record')}}</span>
                 <span class="textInfo">
          <template v-if="tarGetObj.resultValue">{{tarGetObj.resultValue}}</template>
          <template v-else>{{$t('maintenance.none')}}</template>
        </span>
               </div>
             </Col>
             <Col span="6">
               <div class="result">
                 <Col span="4">
                   <span class="text">{{$t('maintenance.Video')}}</span>
                 </Col>
                 <Col span="20">
                   <div class="videoListbox">
                     <template v-if="tarGetObj.attachments && tarGetObj.attachments.length">
                       <div class="itemCol" v-for="(item,index) in tarGetObj.attachments" :key="index">
            <span class="item" @click="previewClicjk(item,index,'target')">
             <template v-if="!item.filePath.includes('video')">
                <img :src="util.filePathToUrl(item.filePath)" alt=""/>
             </template>
              <template v-else>
                 <video preload="auto" loop autoplay muted>
                 <source :src="util.filePathToUrl(item.filePath)" type="video/mp4">
             </video>
              </template>
            </span>
                       </div>
                     </template>
                     <template v-else>
                       <span class="none">{{$t('maintenance.none')}}</span>
                     </template>
                   </div>
                 </Col>
               </div>
             </Col>
           </div>
         </Row>
        </template>
        <div class="spareBox">
          <div class="titleText">
            <span class="item">{{Number($route.query.status) !== 2 ? '备件信息' : '维修信息'}}</span>
            <span class="item" @click="addSpare" style="cursor: pointer">
           {{$t('maintenance.More')}}
          <van-icon class="icon" name="arrow" />
         </span>
          </div>
          <div class="spareList">
            <template v-for="item in listArr">
              <div class="listItem">
                <div class="listTitle">
                  <span> {{$t('maintenance.SparePart')}}</span>
                  <span>{{item.materielNo}}</span>
                </div>
                <div class="list_col">
                  <span class="text">{{$t('maintenance.SpareNumber')}}</span>
                  <span class="value">{{item.materialCode}}</span>
                </div>
                <div class="list_col">
                  <span class="text">{{$t('maintenance.SparePartsName')}}</span>
                  <span class="value">{{item.goodsName}}</span>
                </div>
                <div class="list_col">
                  <span class="text">{{$t('maintenance.Specification')}}</span>
                  <span class="value">{{item.specification}}</span>
                </div>
                <div class="list_col">
                  <span class="text">{{$t('maintenance.usageAmount')}}</span>
                  <span class="value">{{item.num}}</span>
                </div>
                <div class="list_col">
                  <span class="text">{{$t('maintenance.unitprice')}}</span>
                  <span class="value">{{item.unitPrice}}</span>
                </div>
                <div class="listFooter">
                  <span>共{{item.num}}件</span>
                  <div class="moneyBox">
                    <span class="title_m">{{$t('maintenance.totalamount')}}</span>
                    <span class="value">{{item.totalPrice}}</span>
                  </div>
                </div>
              </div>
            </template>
          </div>
          <div class="footerBtn">
            <span class="canler" @click="cancle">{{$t('maintenance.Cancle')}}</span>
            <span class="enter" v-if="showStatus" @click="sumbit">{{$t('maintenance.Save')}}</span>
          </div>
        </div>
      </div>

  <gallery :images="galleryImages" :options="gallyOptions" :index="galleryIndex" @close="galleryIndex = null"></gallery>
</div>
</template>

<script>
import { mapGetters } from 'vuex'
import VueGallery from 'vue-gallery'
import {getDatatools,fileUpload,addfileUpload,delfileUpload} from "@/api/maintenance";
export default {
  name: "detailinfo",
  components:{
    'gallery': VueGallery
  },
  computed: {
    ...mapGetters([
      'detailObj'
    ])
  },
  data(){
    return{
      detailObjCloneClone:[],
      gallyOptions:{
        continuous: false,
      },
      galleryIndex:null,
      galleryImages:[],
      numberStatus:"textarea",
      actions: [{ name: '拍照' }, { name: '视频' }],
      sheetShow:false,
      fileListArr:[],
      fileList:[],
      resultValue:'',
      listArr:[],
      tarLocalinfo:{},
      timerId:'',
      showStatus:true,
      beconfirmed:false,
      tarGetObj:{},
      resultBtn:[
       {title:'正常',active:false,key:1},
       {title:'异常',active:false,key:2}
      ]
  }},
  mounted() {
    this.detailObjClone = JSON.parse(JSON.stringify(this.detailObj))
    this.getDatalist()
    const obj = this.detailObjClone.find(val=>val.itemId == this.$route.query.itemId)
    this.tarGetObj = JSON.parse(JSON.stringify(obj))
    if (obj){
      if (obj.attachments && obj.attachments.length){
        this.fileList = [...obj.attachments]
      }
      if (obj.minValue && obj.maxValue){
        this.numberStatus = 'number'
      }
      this.resultValue = obj.resultValue
      switch (obj.resultStatus) {
        case 1:
          this.tarGetObj.resultStatus = '正常'
              break;
        case 2:
          this.tarGetObj.resultStatus = '异常'
          break;
      }
      this.resultBtn.forEach(val=>{
        val.active = false
        if (val.key === obj.resultStatus){
          val.active = true
        }
      })
    }
    this.$nextTick(()=>{
      if (Number(this.$route.query.status) !== 1){
        this.beconfirmed = true
      }
      if (Number(this.$route.query.status) >=2 ){
        this.showStatus = false
      }else {
        this.showStatus = true
      }
    })
  },
  methods:{
    previewClicjk(item,index,str){
      this.galleryIndex = index
      let arr = []
      if (str === 'target'){
        arr = this.tarGetObj.attachments
      }else {
        arr = this.fileList
      }
      this.galleryImages = arr.map(val=>{
        if(val.filePath.includes('video')){
          val.filetype = 'video/mp4'
        }
        if(val.filePath.includes('jpg')){
          val.filetype = 'image/jpeg'
        }
        return {
          type: val.filetype,
          href: this.util.filePathToUrl(val.filePath),
        }
      })
    },
    checkusetool(){
      const query = {
        itemId:this.$route.query.itemId,
        taskId:this.$route.query.taskId
      }
      this.$router.push({
        path:'/checkusetools',
        query
      })
    },
    oversize(){
      console.log('超过文件大小了')
    },
    dataURLtoFileFun (dataurl, filename) {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    afterRead(file, name) {
      if(file.file.type.indexOf('video') !== -1 || file.file.type.indexOf('image') !== -1){
        let formData = new FormData();
        formData.append("dir", 'device')
        if (file.file.type.indexOf('image') !== -1){
          formData.append("file", this.dataURLtoFileFun(file.content, "file.jpg"));
        }
        if (file.file.type.indexOf('video') !== -1){
          formData.append("file", this.dataURLtoFileFun(file.content, "file.video"));
        }
        let config = {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        }
        fileUpload(formData,config).then(res => {
          if (res.code == 200) {
            res.data.itemId = this.$route.query.itemId
            res.data.taskId = this.$route.query.taskId
            this.fileList.push(res.data)
            const obj = this.detailObjClone.find(val=>val.itemId == this.$route.query.itemId)
            obj.attachments = this.fileList
            this.$store.commit('detail/SET_DETAILOBJ',[...this.detailObjClone])
          }
        })
      }else{
        this.$Message.warning('只能上传视频/图片')
      }
    },
    assetsChange() {
      const tarGetobj = this.detailObjClone.find(val=>val.itemId == this.$route.query.itemId)
      if (!this.resultValue){
        return
      }
      if (this.numberStatus !== 'number'){
        tarGetobj.resultValue = this.resultValue
        this.$store.commit('detail/SET_DETAILOBJ',[...this.detailObjClone])
        return
      }
      if (this.timerId) {
        clearTimeout(this.timerId)
      }
      this.timerId = setTimeout(() => {
       if (this.resultValue >= Number(tarGetobj.minValue) && this.resultValue <= Number(tarGetobj.maxValue)){
         this.resultBtn = [
           {title:'正常',active:true,key:1},
           {title:'异常',active:false,key:2}
         ]
       }else {
         this.resultBtn = [
           {title:'正常',active:false,key:1},
           {title:'异常',active:true,key:2}
         ]
       }
        tarGetobj.resultValue = this.resultValue
        tarGetobj.resultStatus = this.resultBtn.find(val=>val.active === true).key
        this.$store.commit('detail/SET_DETAILOBJ',[...this.detailObjClone])
      }, 550)
    },
    getDatalist(){
      this.listArr = []
      const { itemId,taskId } = this.$route.query
      getDatatools({ itemId,taskId }).then(res=>{
        if (res.data.materialList && res.data.materialList.length){
          this.listArr = this.listArr.concat(res.data.materialList)
        }
      })
    },
    addSpare(){
      const query = {
        itemId:this.$route.query.itemId,
        taskId:this.$route.query.taskId,
        orgId:this.$route.query.orgId,
        status:this.$route.query.status,
        itemProject:this.$route.query.itemProject
      }
      this.$router.push({
        path:'/addspare',
        query
      })
    },
    async delFujian(item){
      if (item.id){
        const params = {
          id:item.id
        }
        const {data} = await delfileUpload(params)
        if (data === '删除成功!'){
          this.fileList = this.fileList.filter(val=>val.fileUrl !== item.fileUrl)
          const obj = this.detailObjClone.find(val=>val.itemId == this.$route.query.itemId)
          obj.attachments = obj.attachments.filter(val=>val.fileUrl !== item.fileUrl)
          this.$store.commit('detail/SET_DETAILOBJ',[...this.detailObjClone])
        }
      }else {
        this.fileList = this.fileList.filter(val=>val.fileUrl !== item.fileUrl)
      }
    },
    async sumbit(){
      if (!this.resultValue){
        this.$Message.warning('结果记录未填写');
        return
      }
      if (this.fileList && this.fileList.length){
        const data = this.fileList.map(val=>({
          itemId:val.itemId,
          taskId:val.taskId,
          fileName:val.fileName,
          filePath:val.filepath,
          fileUrl:val.fileUrl
        }))
        addfileUpload(data)
      }
      this.$store.commit('detail/SET_DETAILOBJ',[...this.detailObjClone])
      this.$store.commit('detail/SET_SUMBITSTATUS',true)
      this.$router.go(-1)
    },
    cancle(){
      if (!this.tarGetObj.resultStatus){
        this.$store.commit('detail/SET_DETAILOBJ',[])
        this.$store.commit('detail/SET_SUMBITSTATUS',false)
      }
      if (this.$route.query.callback == 2){
        this.$router.go(-2)
      }else {
        this.$router.go(-1)
      }
    },
    btnCick(row){
      const obj = this.detailObjClone.find(val=>val.itemId == this.$route.query.itemId)
      if (this.numberStatus === 'number'){
        return
      }
       this.resultBtn.forEach(val=>val.active = false)
       this.$set(row,'active',true)
       obj.resultStatus = row.key
      this.$store.commit('detail/SET_DETAILOBJ',[...this.detailObjClone])
    }
  }
}
</script>

<style scoped lang="scss">
@import "index.scss";
</style>
